package org.dj.eoms.system.web.listener;

import org.apache.log4j.LogManager;
import org.apache.log4j.PropertyConfigurator;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.File;
import java.io.InputStream;
import java.util.Properties;

/**
 * Created by DengJun on 16/1/14.
 */
public class Log4jInitListener implements ServletContextListener {
    public void contextInitialized(ServletContextEvent event) {
        //缺省为当前应用程序主目录
        String log_Path = event.getServletContext().getRealPath("/logs");

        try {
            File logDir = new File(log_Path);
            if (!logDir.exists()) {
                if (!logDir.mkdirs()) {
                    throw new Exception("创建日志目录失败!");

                }
            }

            InputStream fis = this.getClass().getResourceAsStream("/config/common/log4j.properties");
            //配置Log4j
            if (fis != null){
                Properties prop = new Properties();
                prop.load(fis);
                prop.setProperty("log4j.appender.fileout.File",log_Path + "/eoms.log");
                PropertyConfigurator.configure(prop);

                //关闭流文件
                fis.close();
            }

        } catch (Exception e) {
            event.getServletContext().log("配置Log4j日志错误:",e);
            e.printStackTrace();
        }

    }

    public void contextDestroyed(ServletContextEvent event) {

        event.getServletContext().log("关闭Log4j日志!");
        LogManager.shutdown();

    }
}
